﻿using LDC_Shop_B.Models;
using LDC_Shop_B.Models.Database;
using LDC_Shop_B.Serives;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Security.Claims;
using System.Transactions;

namespace LDC_Shop_B.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly ICarService _carService;
        private readonly IOrderService _orderService;
        private readonly LDC_ShopBContext _db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="carService"></param>
        public OrderController(ICarService carService, IOrderService orderService, LDC_ShopBContext db)
        {
            _carService = carService;
            _orderService = orderService;
            _db = db;
        }

        //结算（把购物车商品生成订单和订单明细，进行结算，扣除商品库存，订单进入待发货状态【支付功能略过】）
        /// <summary>
        /// 订单结算
        /// </summary>
        [Authorize]
        [HttpPost]
        public string Settlement()
        {
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    //1、获取购物车商品
                    //我  登录的用户 Token中获取用户信息
                    var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
                    //查询购物车商品
                    var list = _carService.GetCarGoodsForSQL(Convert.ToInt32(userId));
                    if (list.Count == 0)
                    {
                        return "购物车没有商品";
                    }

                    //插入步骤 检查库存
                    //如果库存不足返回false  判断的是有库存
                    if (!_orderService.CheckGoodStock(list, out string err))
                    {
                        return $"[{err}]商品库存不足";
                    }

                    //2、把商品生成订单和订单明细表 同时添加两个表
                    _orderService.CreateOrder(list, Convert.ToInt32(userId));

                    //3、扣除商品库存   库存没了
                    _orderService.DiffGoodStock(list);

                    //4、清空购物车
                    _carService.RemoveCarForSQL(Convert.ToInt32(userId));

                    //提交事务
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    // 处理异常
                    return "结算错误";
                }
            }
            //4、完成
            return "结算完成";
        }


        //用户按照订单的状态查询自己的订单列表，查看订单商品，订单价格，订单状态等
        /// <summary>
        /// 订单列表
        /// </summary>
        [Authorize]
        [HttpPost]
        public GetUserOrderListResponse GetUserOrderList(GetUserOrderListRequest request)
        {
            //用户Id
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //获取用户的订单列表
            var orderList = _orderService.GetUserOrderList(Convert.ToInt32(userId), request.OrderState, request.PageIndex, request.PageSize, out int total);
            //构建返回类
            var response = new GetUserOrderListResponse
            {
                List = orderList,
                Total = total
            };
            return response;
        }

        //后台订单列表（查询所有用户下的订单，查询订单号，订单价格，下单用户，订单商品）
        /// <summary>
        /// 后台订单列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GetAdminOrderListResponse AdminOrderList(GetUserOrderListRequest request)
        {
            //获取用户的订单列表
            var orderList = _orderService.GetAdminOrderList(request.OrderState, request.PageIndex, request.PageSize, out int total);
            //构建返回类
            var response = new GetAdminOrderListResponse
            {
                List = orderList,
                Total = total
            };
            return response;
            
        }
        /// <summary>
        /// 发货
        /// </summary>
        /// <returns></returns>
        public string SendOrder(SendOrderRequest request)
        {
           var result= _orderService.SendOrder(request.OrderId, request.ShipCom, request.ShipNum);
            if (result)
                return "发货成功";
            return "发货失败";
        }

        /// <summary>
        /// 事务例子
        /// </summary>
        [HttpGet]
        public void Fun()
        {
            //using (定义的对象)只会在
            //{
            //    这里使用
            //}
            // 出个这个地方就会自动销毁对象
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {

                    //下单
                    _db.OrderItems.Add(new OrderItem()
                    {
                        OrderId = 1,
                        GoodCount = 1,
                        GoodCover = "",
                        GoodId = 2,
                        GoodName = "商品名称",
                        GoodPrice = 12,
                    });

                    // 扣除库存
                    var good = _db.Goods.FirstOrDefault(x => x.GoodId == 2);
                    good.Stock -= 1;
                    _db.Goods.Update(good);
                    _db.SaveChanges();
                    // 如果所有的操作都执行成功，则Complete()会被调用来提交事务
                    // 如果发生异常，则不会调用它并回滚事务
                    //提交事务
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    // 处理异常
                }
            }
            //执行完成了
        }

    }
}
